package com.hmys.api.service;

import com.hmys.api.mapper.WebTokenMapper;
import com.hmys.api.model.WebToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by philip on 5/19/17.
 */
@Service
public class LoginPersistenceService implements PersistentTokenRepository {
    @Autowired
    WebTokenMapper tokenMapper;

    @Override
    public void createNewToken(PersistentRememberMeToken persistentRememberMeToken) {
        WebToken token = new WebToken();
        token.setUsername(persistentRememberMeToken.getUsername());
        token.setLastUsed(persistentRememberMeToken.getDate());
        token.setSeries(persistentRememberMeToken.getSeries());
        token.setTokenValue(persistentRememberMeToken.getTokenValue());
        tokenMapper.insert(token);
    }

    @Override
    public void updateToken(String series, String tokenValue, Date date) {
        WebToken token = tokenMapper.selectBySeries(series);
        if (token == null) return;
        token.setTokenValue(tokenValue);
        token.setLastUsed(date);
        tokenMapper.updateByPrimaryKeySelective(token);
    }

    @Override
    public PersistentRememberMeToken getTokenForSeries(String series) {
        WebToken token = tokenMapper.selectBySeries(series);
        if (token == null) return null;
        return new PersistentRememberMeToken(token.getUsername(), token.getSeries(), token.getTokenValue(), token.getLastUsed());
    }

    @Override
    public void removeUserTokens(String series) {
        WebToken token = tokenMapper.selectBySeries(series);
        if (token == null) return;
        tokenMapper.deleteByPrimaryKey(token.getId());
    }
}
